import { error } from "util"

const whole = {
  id: 0,
  name: "全国",
  level: 2,
  upid: 0
}

export default {
  state: {
    provinces: [],
    provincesWithWhole: [
      {
        id: 0,
        name: "全国",
        level: 1,
        upid: 0
      }
    ],
    citys: {},
    citysWithWhole: { 0: [whole] },
    areas: {},
    towns: {}
  },
  mutations: {
    initProvinces(state, provinces) {
      state.provinces = state.provinces.concat(provinces)
      state.provincesWithWhole = state.provincesWithWhole.concat(provinces)
    },
    insertCitys(state, { citys, pid }) {
      state.citys[pid] = citys
      let c = citys.slice()
      c.unshift(whole)
      state.citysWithWhole[pid] = c
    },
    insertAreas(state, { areas, cid }) {
      state.areas[cid] = areas
    },
    insertTowns(state, { towns, aid }) {
      state.towns[aid] = towns
    }
  },
  actions: {
    async getProvinces({ commit, state, dispatch }) {
      if (state.provinces.length === 0) {
        const provinces = await dispatch("callDistrictApi")
        commit("initProvinces", provinces)
      }
      return state.provinces
    },
    async getProvincesWithWhole({ commit, state, dispatch }) {
      if (state.provincesWithWhole.length === 1) {
        const provinces = await dispatch("callDistrictApi")
        commit("initProvinces", provinces)
      }
      return state.provincesWithWhole
    },
    async getCity({ commit, state, dispatch }, pid) {
      if (!state.citys[pid]) {
        const citys = await dispatch("callDistrictApi", pid)
        commit("insertCitys", { citys, pid })
      }
      return state.citys[pid]
    },
    async getCityWithWhole({ commit, state, dispatch }, pid) {
      if (!state.citysWithWhole[pid]) {
        const citys = await dispatch("callDistrictApi", pid)
        commit("insertCitys", { citys, pid })
      }
      return state.citysWithWhole[pid]
    },
    async getAreas({ commit, state, dispatch }, cid) {
      if (!state.areas[cid]) {
        const areas = await dispatch("callDistrictApi", cid)
        commit("insertAreas", { areas, cid })
      }
      return state.areas[cid]
    },
    async getTowns({ commit, state, dispatch }, aid) {
      if (!state.towns[aid]) {
        const towns = await dispatch("callDistrictApi", aid)
        commit("insertTowns", { towns, aid })
      }
      return state.towns[aid]
    },
    async callDistrictApi({ commit, state }, upid = 0) {
      let res
      if (!upid) {
        res = await axios.get("/api/common/getDistrict")
      } else {
        res = await axios.get("/api/common/getDistrict", {
          params: {
            upid: upid
          }
        })
      }

      let data = res.data
      if (data.resp_msg.msg_code === 200) {
        // commit("initProvinces", data.resp_data)
        return data.resp_data
      } else {
        throw new error(
          `Can not get district, code is ${data.resp_msg.msg_code}`
        )
      }
    }
  }
}
